<template>
  <div>
    <!-- 表单组件 -->
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="formConfig.rules"
      label-width="100px"
    >
      <el-form-item
        v-for="item in formConfig.items"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
      >
        <el-input
          v-if="item.type == 'Text'"
          type="text"
          clearable
          v-model="formModel[item.prop]"
          :placeholder="item.placeholder"
        />
        <el-input
          v-if="item.type == 'Textarea'"
          type="textarea"
          clearable
          v-model="formModel[item.prop]"
          :placeholder="item.placeholder"
        />
        <el-select
          v-if="item.type == 'Select'"
          v-model="formModel[item.prop]"
          :style="{ width }"
          clearable
          :placeholder="item.placeholder"
        >
          <el-option
            v-for="i in formConfig.optionList"
            :label="i.label"
            :value="i.value"
          ></el-option>
        </el-select>
        <el-date-picker
          v-if="item.type == 'Date'"
          :style="{ width }"
          v-model="formModel[item.prop]"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSure">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<!-- vue3 表单组件 -->
<script setup>
/*
  表单的循环结构
    [{
      // 标签
      label: "姓名",  
      // 表单接收值
      prop: "name",
      // 当前组件类型
      type: "Text",
      placeholder: '请输入名称'
    }]
*/
/*
  表单校验
    name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    level: [{ required: true, message: "请选择年级", trigger: "change" }],
    date: [{ required: true, message: "请选择日期", trigger: "change" }],
*/
/*
  下拉列表
    {
      label: "一年级",
      value: 1,
    },
*/
import { defineProps, ref, reactive } from "vue";
let props = defineProps({
  /**
   * 组件宽度
   */
  width: {
    type: String,
    default: () => "100%",
  },
  /**
   * 表单配置
   */
  formConfig: {
    type: Object,
    default: () => {},
  },
});

// 表单ref
let formRef = ref();
// 绑定表单
let formModel = reactive({});
let optionArr = ref([]);
/**
 * 确定
 */
function handleSure() {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log("formModel", formModel);
    } else {
      return false;
    }
  });
}
/**
 * 取消
 */
function handleCancel() {
  formRef.value.resetFields();
}
</script>

<style scoped></style>
